/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.example.activity.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.oraycn.esbasic.helpers.ImageHelper;
import com.oraycn.esbasic.tools.imageCropper.CropIntent;
import com.oraycn.esbasic.views.NiceImageView;

import net.example.activity.ChangePasswordActivity;
import net.example.activity.MainActivity;
import net.example.activity.UpdatePropertyActivity;
import net.example.activity.adapter.KeyValuePairAdpter;
import net.example.ggtalk.R;
import net.example.manager.ClientGlobalCache;
import net.example.manager.Manager;
import net.example.model.GGUser;
import net.example.model.KeyValuePairModel;
import net.example.model.UpdatePropertyType;
import net.example.model.event.MyPhoneChangedEvent;
import net.example.model.event.UserHeadImageChangedEvent;
import net.example.model.event.UserInfoChangedEvent;
import net.example.utils.HeadImgHelper;
import net.example.utils.IntentUtils;
import net.example.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * 设置界面
 * 
 * @author Administrator
 * 
 */
public class SettingsFragment extends Fragment implements OnClickListener, AdapterView.OnItemClickListener {
	public static final String CROPPED_IMAGE_FILEPATH = "/sdcard/cropped.jpg";

	/**
	 * 退出按钮
	 */
	private ImageButton logoutBtn;

	/**
	 * 诊断
	 */
	private LinearLayout llDiagnose;
	NiceImageView iv_header;
	private TextView tv_userID;
	private TextView tv_userName;
	private ListView listView;
	private KeyValuePairAdpter lv_adpter, lv_adpter2;
	private List<KeyValuePairModel> lv_modelList,lv_modelList2;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_conversation_settings,
				container, false);

	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		TextView tv_title = (TextView) getView().findViewById(R.id.message_title);
		tv_title.setText(R.string.set);
		getView().findViewById(R.id.plus_btn).setVisibility(View.GONE);
		this.initUserDetailHeadView();
		this.initListView();
		this.initListView2();
		logoutBtn = (ImageButton) getView().findViewById(R.id.btn_logout);
		logoutBtn.setOnClickListener(this);
	}

	//初始化头部试图
	private void initUserDetailHeadView()
	{
		if (!EventBus.getDefault().isRegistered(this)) {
			EventBus.getDefault().register(this);
		}

		iv_header =(NiceImageView)  getView().findViewById(R.id.avatar);
		HeadImgHelper.setUserHeadImg(iv_header,ClientGlobalCache.getInstance().getCurrentUser());
		iv_header.setOnClickListener(this);
		tv_userID=(TextView)  getView().findViewById(R.id.userDetail_userID);
		TextView tv_userName1 =(TextView)  getView().findViewById(R.id.userName);
		tv_userName1.setVisibility(View.GONE);
		tv_userName=(TextView)getView().findViewById(R.id.commentName);
		tv_userName.setText(ClientGlobalCache.getInstance().getCurrentUser().getName());
		tv_userID.setText("账号：" + ClientGlobalCache.getInstance().getCurrentUser().getUserID());
	}

	private void initListView()
	{
		listView =(ListView)getView().findViewById(R.id.lv_key_value);
		lv_modelList=new ArrayList<>();
		this.getModelList();
		lv_adpter=new KeyValuePairAdpter(lv_modelList,getActivity(),true);
		listView.setAdapter(lv_adpter);
		listView.setOnItemClickListener(this);
	}

	private void getModelList()
	{
		lv_modelList.clear();
		lv_modelList.add(new KeyValuePairModel(R.drawable.name_icon ,getResources().getString(R.string.name),ClientGlobalCache.getInstance().getCurrentUser().getName()));
		lv_modelList.add(new KeyValuePairModel(R.drawable.autograph_icon, getResources().getString(R.string.user_signature),ClientGlobalCache.getInstance().getCurrentUser().getSignature()));
	}

	private void initListView2()
	{
		ListView listView2 =(ListView)getView().findViewById(R.id.lv_key_value2);
		lv_modelList2=new ArrayList<>();
		lv_modelList2.add(new KeyValuePairModel(R.drawable.update_password, getResources().getString(R.string.update_password),""));
		lv_modelList2.add(new KeyValuePairModel(R.drawable.update_phone, getResources().getString(R.string.update_phone),ClientGlobalCache.getInstance().getCurrentUser().Phone));
		lv_adpter2=new KeyValuePairAdpter(lv_modelList2,getActivity(),true);
		listView2.setAdapter(lv_adpter2);
		listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				KeyValuePairModel model=lv_modelList2.get(position);
				if(model.Key.equals(getResources().getString(R.string.update_phone)))
				{
					IntentUtils.startActivityForString(getActivity(), UpdatePropertyActivity.class, getResources().getString(R.string.update_property_type), UpdatePropertyType.Phone.toString());
				}
				else if(model.Key.equals(getResources().getString(R.string.update_password)))
				{
//					ToastUtils.showShort(getContext(),"功能暂未开通");
					Intent intent=new Intent(getContext(), ChangePasswordActivity.class);
					intent.putExtra("phone",ClientGlobalCache.getInstance().getCurrentUser().Phone);
					startActivityForResult(intent, 2);
				}
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.avatar: //点击更换头像
				// Create a CropIntent
				CropIntent cropIntent = new CropIntent();
				// Set the source image filepath/URL and output filepath/URL (Optional)
				//intent.setImagePath("/sdcard/source.jpg");
				cropIntent.setOutputPath(CROPPED_IMAGE_FILEPATH);

				// Set a fixed crop window size (Optional)
//				intent.setOutputSize(300,300);

				// set the max crop window size (Optional)
//				intent.setMaxOutputSize(400,300);

				// Set a fixed crop window's width/height aspect (Optional)
//				intent.setAspect(1,1);

				//选择框是否为正方形
				cropIntent.setDrawSquare(true);

				// start ImageCropper activity with certain request code and listen for result
				startActivityForResult(cropIntent.getIntent(getActivity()), 0);
			break;
		case R.id.btn_logout: // 退出登陆
			Manager.getInstance().logout();
			break;
		default:
			break;
		}

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		if (resultCode != getActivity().RESULT_OK) {
			return;
		}
		if (requestCode == 0) {
			try {
				Uri croppedUri = intent.getExtras().getParcelable(MediaStore.EXTRA_OUTPUT);
//				BitmapFactory.Options options=new BitmapFactory.Options();
//				Bitmap b= BitmapFactory.decodeByteArray(data,0,data.length,options);
//				Bitmap b= BitmapFactory.decodeFile(croppedUri.getPath());
				Bitmap b=MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), croppedUri);
				iv_header.setImageBitmap(b);
				byte[] data=null;
				if(b.getWidth()>300||b.getHeight()>300)
				{
					data = ImageHelper.getZoomImageToByteArray(b,300,300,false);
				}
				else {
					data= ImageHelper.bitmapToByteArray(b,false);
				}
				Manager.getInstance().changeMyHeadImage(-1,data);
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
		else if(requestCode==1)//更换手机号
		{
			ToastUtils.showShort(getContext(),"更换成功！");
		}else if(requestCode==2)//重置密码
		{

		}

	}

	public void onEventMainThread(UserInfoChangedEvent event)
	{
		if(event.UserID.equals(ClientGlobalCache.getInstance().getCurrentUser().getUserID()))
		{
//			HeadImgHelper.setUserHeadImg(iv_header,ClientGlobalCache.getInstance().getCurrentUser());
			GGUser GGUser = ClientGlobalCache.getInstance().getUser(event.UserID);
			tv_userName.setText(GGUser.getName());
			this.getModelList();
			lv_adpter.notifyDataSetChanged();
			this.changePhone4View(GGUser.Phone);
		}
	}

	public void onEventMainThread(UserHeadImageChangedEvent event){
		if(event.UserID.equals(ClientGlobalCache.getInstance().getCurrentUser().getUserID()))
		{
			HeadImgHelper.setUserHeadImg(iv_header,ClientGlobalCache.getInstance().getCurrentUser());
		}
	}

	public void onEventMainThread(MyPhoneChangedEvent event)
	{
		this.changePhone4View(event.NewPhone);
	}

	//更新页面上的手机号显示
	private void changePhone4View(String newPhone)
	{
		for (KeyValuePairModel model :lv_modelList2)
		{
			if(model.Key.equals(getResources().getString(R.string.update_phone)))
			{
				model.Value=newPhone;
			}
		}
		this.lv_adpter2.notifyDataSetChanged();
	}

	// 保存当前activity登录状态
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		if (((MainActivity) getActivity()).isConflict) {
		} else if (((MainActivity) getActivity()).getCurrentAccountRemoved()) {
		}
	}

	@Override
	public void onDestroyView(){
		super.onDestroyView();
		EventBus.getDefault().unregister(this);
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

		KeyValuePairModel model=this.lv_modelList.get(position);
		try {
			if(model.Key.equals(getResources().getString(R.string.name)))
			{
				IntentUtils.startActivityForString(getActivity(), UpdatePropertyActivity.class, getResources().getString(R.string.update_property_type), UpdatePropertyType.UserName.toString());
			}
			else if(model.Key.equals(getResources().getString(R.string.user_signature)))
			{
				IntentUtils.startActivityForString(getActivity(),UpdatePropertyActivity.class, getResources().getString(R.string.update_property_type), UpdatePropertyType.UserSignature.toString());
			}


		}catch (Exception ee) {
			ee.printStackTrace();
		}

	}


}
